/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.test.runner;

import com.mongodb.Mongo;
import lombok.Getter;
import org.jrose.test.annotation.CleanupCollections;
import org.jrose.test.annotation.CleanupTables;
import org.jrose.test.annotation.CleanupUsers;
import org.jrose.test.support.PrepareDatabaseTables;
import org.jrose.test.support.PrepareMongoCollections;
import org.junit.runner.Description;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.springframework.context.ApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.jdbc.support.JdbcUtils;

import javax.sql.DataSource;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Spring junit4 test runner implementation which can auto detect if test database
 * is available or not, if not, ignore the test method.
 *
 * @author Xiaohai Zhang
 * @since 2013-08-17 15:16
 */
public class ExtendedTestRunner extends AbstractTestRunner {
    private static final Set<Class<? extends Annotation>> databaseCleanupAnnotations;
    private static final Set<Class<? extends Annotation>> mongoCleanupAnnotations;

    static {
        databaseCleanupAnnotations = new LinkedHashSet<>();
        databaseCleanupAnnotations.add(CleanupTables.class);
        databaseCleanupAnnotations.add(CleanupUsers.class);

        mongoCleanupAnnotations = new LinkedHashSet<>();
        mongoCleanupAnnotations.add(CleanupCollections.class);
        mongoCleanupAnnotations.add(CleanupUsers.class);
    }

    public ExtendedTestRunner(Class<?> clazz) throws InitializationError {
        super(clazz);
    }

    @Override
    protected boolean doRunChild(FrameworkMethod frameworkMethod, RunNotifier notifier) {
        DatabaseConnectionManager.initialize(getApplicationContext());
        MongoConnectionManager.initialize(getApplicationContext());

        boolean cleanupDatabase = false;
        for (Class<? extends Annotation> databaseCleanupAnnotation : databaseCleanupAnnotations) {
            if (frameworkMethod.getAnnotation(databaseCleanupAnnotation) != null) {
                cleanupDatabase = true;
                break;
            }
        }
        if (cleanupDatabase) {
            if (!DatabaseConnectionManager.isAvailable()) {
                Description description = describeChild(frameworkMethod);
                notifier.fireTestIgnored(description);
                return false;
            } else {
                DataSource dataSource = DatabaseConnectionManager.getDataSource();
                new PrepareDatabaseTables(frameworkMethod, dataSource).prepare();
            }
        }

        boolean cleanupMongo = false;
        for (Class<? extends Annotation> mongoCleanupAnnotation : mongoCleanupAnnotations) {
            if (frameworkMethod.getAnnotation(mongoCleanupAnnotation) != null) {
                cleanupMongo = true;
                break;
            }
        }
        if (cleanupMongo) {
            if (!MongoConnectionManager.isAvailable()) {
                Description description = describeChild(frameworkMethod);
                notifier.fireTestIgnored(description);
                return false;
            } else {
                MongoTemplate mongoTemplate = MongoConnectionManager.getMongoTemplate();
                new PrepareMongoCollections(frameworkMethod, mongoTemplate).prepare();
            }
        }
        return true;
    }

    private static class DatabaseConnectionManager {
        private static final AtomicBoolean initialized = new AtomicBoolean(false);

        @Getter private static DataSource dataSource = null;
        @Getter private static boolean available = false;

        static void initialize(ApplicationContext applicationContext) {
            if (initialized.get()) {
                return;
            }
            try {
                dataSource = applicationContext.getBean(DataSource.class);
                Connection connection = null;
                try {
                    connection = dataSource.getConnection();
                    connection.getAutoCommit();
                    available = true;
                } finally {
                    JdbcUtils.closeConnection(connection);
                }
            } catch (Exception ignored) {
                // ignored
            } finally {
                initialized.set(true);
            }
        }
    }

    private static class MongoConnectionManager {
        private static final AtomicBoolean initialized = new AtomicBoolean(false);

        @Getter private static MongoTemplate mongoTemplate = null;
        @Getter private static boolean available = false;

        static void initialize(ApplicationContext applicationContext) {
            if (initialized.get()) {
                return;
            }
            try {
                String className = "org.jrose.core.mongo.MongoConnection";
                Class<?> mongoConnectionClazz = ExtendedTestRunner.class.getClassLoader().loadClass(className);

                Object mongoConnection = applicationContext.getBean(mongoConnectionClazz);

                Method method = mongoConnectionClazz.getMethod("getMongo");
                Mongo mongo = (Mongo) method.invoke(mongoConnection);

                available = mongo.getConnectPoint() != null;

                if (available) {
                    mongoTemplate = new MongoTemplate(mongo, "test");
                    mongoTemplate.setApplicationContext(applicationContext);
                }
            } catch (Exception ignored) {
                // ignored
                ignored.printStackTrace();
            } finally {
                initialized.set(true);
            }
        }
    }
}
